package godau.fynn.dsbdirect.manager;

import android.content.Context;
import godau.fynn.dsbdirect.Utility;
import godau.fynn.dsbdirect.table.Shortcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ShortcodeManager {

    private Context context;
    private Shortcode[] shortcodes;

    public ShortcodeManager(Context context) {
        this.context = context;
    }

    public Shortcode[] read() {

        Set<String> shortcodeSet = new Utility(context).getSharedPreferences().getStringSet("shortcodes", new HashSet<String>());
        String[] shortcodeStrings = shortcodeSet.toArray(new String[shortcodeSet.size()]);

        Shortcode[] shortcodes = new Shortcode[shortcodeSet.size()];

        for (int i = 0; i < shortcodeSet.size(); i++) {
            try {
                shortcodes[i] = new Shortcode(shortcodeStrings[i]);
            } catch (IllegalArgumentException e) {
                // Better not be null
                shortcodes[i] = new Shortcode("", "");
                e.printStackTrace();
            }
        }

        this.shortcodes = shortcodes;

        return shortcodes;
    }

    public void write(Shortcode[] shortcodes) {
        this.shortcodes = shortcodes;

        String[] shortcodeStrings = new String[shortcodes.length];

        for (int i = 0; i < shortcodes.length; i++) {
            shortcodeStrings[i] = shortcodes[i].serialize();
        }

        new Utility(context).getSharedPreferences()
                .edit()
                .putStringSet("shortcodes", new HashSet<String>(Arrays.asList(shortcodeStrings)))
                .apply();

    }

    public String replace(String s) {
        if (shortcodes == null) {
            read();
        }
        for (Shortcode shortcode :
                shortcodes) {
            if (shortcode.containedIn(s)) {
                s = shortcode.replace(s);
                break;
            }
        }
        return s;
    }

}
